package apple.eclipse.model;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;

import apple.core.Apple;

public class Model {

   private static final Model model = new Model();

   public static final String PROPERTY_NAME = "modelChange";

   private List<Apple> apples;

   private List<PropertyChangeListener> listeners;

   private Model() {
      listeners = new ArrayList<PropertyChangeListener>();
      apples = new ArrayList<Apple>();
   }

   public static Model getInstance() {
      return model;
   }

   public void addApple(Apple apple) {
      apples.add(apple);
      PropertyChangeEvent event = new PropertyChangeEvent(apple, PROPERTY_NAME,
            null, apple);
      firePropertyChange(event);
   }

   public void removeApple(Apple apple) {
      apples.remove(apple);
      PropertyChangeEvent event = new PropertyChangeEvent(apple, PROPERTY_NAME,
            apple, null);
      firePropertyChange(event);
   }

   public Apple[] getApples() {
      return apples.toArray(new Apple[apples.size()]);
   }

   public void addPropertyChangeListener(PropertyChangeListener listener) {
      if (!listeners.contains(listener)) {
         listeners.add(listener);
      }
   }

   public void removePropertyChangeListener(PropertyChangeListener listener) {
      listeners.remove(listener);
   }

   protected void firePropertyChange(PropertyChangeEvent event) {
      for (PropertyChangeListener listener : listeners) {
         listener.propertyChange(event);
      }
   }
}
